package com.mr.web.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.mr.model.BaseInfo;
import com.mr.model.Config;
import com.mr.model.Culture;
import com.mr.model.Discount;
import com.mr.model.Elegant;
import com.mr.model.Goods;
import com.mr.model.GoodsOrder;
import com.mr.model.GoodsType;
import com.mr.model.Member;
import com.mr.model.News;
import com.mr.model.Plan;
import com.mr.model.Proxy;
import com.mr.model.QQInfo;
import com.mr.model.SearchCommand;
import com.mr.model.Shop;
import com.mr.model.Status;
import com.mr.model.User;
import com.mr.model.Video;
import com.mr.util.DesUtils;
import com.mr.util.RandomUtil;
import com.mr.util.StringUtil;
import com.mr.util.ValidateUtil;
import com.mr.web.support.PageUtil;

@Controller
public class CompanyController extends AnnotationController {
	//添加代理公司
	@RequestMapping("/auth/member/company/proxyForm.xhtml")
	public String proxyForm(Long id, ModelMap model) {
		model.put("isMod", true);
		if(id!=null){
			Proxy proxy = daoService.getObject(Proxy.class, id);
			model.put("proxy", proxy);
		}
		return "proxy/proxyForm.vm";	
	}
	@RequestMapping("/auth/member/company/proxyDetail.xhtml")
	public String proxyDetail(Long id, ModelMap model) {
		if(id!=null){
			Proxy proxy = daoService.getObject(Proxy.class, id);
			model.put("proxy", proxy);
		}
		return "proxy/proxyForm.vm";
	}
	@RequestMapping("/auth/common/accountPwd.xhtml")
	public String proxyPwd(String enId, ModelMap model) {
		Long id = Long.valueOf(DesUtils.decrypt(enId));
		Member member = daoService.getObject(Member.class, id);
		if(member==null) return forwadMessage(model, "账户不存在！");
		model.put("member", member);
		return "company/accountPwd.vm";
	}
	@RequestMapping("/auth/member/company/proxyList.xhtml")
	public String proxyList(SearchCommand command, Integer pageNo, ModelMap model) {
		if(pageNo==null) pageNo = 0;
		Integer limit = 15;
		Integer count = commonService.getProxyCount(command);
		List<Proxy> proxyList = commonService.getProxyList(command, pageNo*limit, limit);
		
		Integer rowsPerPage = limit;
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/proxyList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("pageUtil", pageUtil);
		
		model.put("proxyList", proxyList);
		model.put("count", count);
		return "proxy/proxyList.vm";
	}
	@RequestMapping("/auth/member/company/updateProxy.xhtml")
	public String updateProxy(Long id, ModelMap model) {
		Proxy proxy = daoService.getObject(Proxy.class, id);
		proxy.setStatus(Status.D);
		daoService.saveObject(proxy);
		return showJsonSuccess(model);
	}
	//保存代理公司
	@RequestMapping("/auth/member/company/saveProxy.xhtml")
	public String saveProxy(Long id, HttpServletRequest req, ModelMap model) {
		Proxy proxy = new Proxy();
		if(id!=null) {
			proxy = daoService.getObject(Proxy.class, id);
		}else {
			BaseInfo base = (BaseInfo)req.getSession().getAttribute("base");
			String membername = RandomUtil.getRandChar(6);
			String p = RandomUtil.getRandNum(8);
			String password = StringUtil.md5(p);
			String pwd = DesUtils.encrypt(p);
			Member member = new Member(membername, password, pwd, Member.MEMBERTYPE_PROXY, base);
			daoService.saveObject(member);
			id = member.getId();
		}
		try {
			bindData(proxy, req.getParameterMap());
			proxy.setId(id);
			String msg = ValidateUtil.validate(proxy, ",");
			if(StringUtils.isNotBlank(msg)) return showJsonFailure(msg, model);
			daoService.saveObject(proxy);
		} catch (Exception e) {
			e.printStackTrace();
			return showJsonFailure("保存数据出错！", model);
		}
		model.put("id", proxy.getId());
		return showJsonSuccess(model);
	}
	//添加物品
	@RequestMapping("/auth/member/company/goodsForm.xhtml")
	public String goodsForm(Long id, ModelMap model) {
		if(id!=null) {
			Goods goods = daoService.getObject(Goods.class, id);
			model.put("goods", goods);
		}
		List<GoodsType> typeList = daoService.getAllObjects(GoodsType.class);
		model.put("typeList", typeList);
		return "company/goodsForm.vm";
	}
	//保存物品
	@RequestMapping("/auth/member/company/saveGoods.xhtml")
	public String saveGoods(Long id, HttpServletRequest req, ModelMap model) {
		BaseInfo base = (BaseInfo)req.getSession().getAttribute("base");
		Long relatedid = base.getId();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
		MultipartFile file = multipartRequest.getFile("file");
		Goods goods = new Goods();
		if(id!=null) {
			goods = daoService.getObject(Goods.class, id);
			if(goods==null) return showJsonFailure("数据不存在！", model);
		}else {
			goods.setRelatedid(relatedid);
			goods.setParentid(0L);
		}
		try{
			bindData(goods, req.getParameterMap());
			String msg = ValidateUtil.validate(goods, ",");
			if(StringUtils.isNotBlank(msg)) return showJsonFailure(msg, model);
			if(id==null) goods.setRemain(goods.getQuantity());
			BigDecimal dec = new BigDecimal(goods.getProxyPrice());
			dec.setScale(1);
			goods.setProxyPrice(dec.doubleValue());
			if(file!=null && file.getSize()>0){
				byte[] buffer = new byte[1024];
				int len = -1;
				InputStream in = file.getInputStream();
				String fileName = StringUtil.getNewFileName(file);
				String path = req.getSession().getServletContext().getRealPath("/upload/images") + "/" + fileName;
				OutputStream out = new FileOutputStream(path);
				while ((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				in.close();
				out.close();
				goods.setLogo("upload/images/"+fileName);
			}
			daoService.saveObject(goods);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/auth/member/company/goodsList.xhtml";
	}
	@RequestMapping("/auth/member/company/goodsList.xhtml")
	public String goodsList(String name, Integer pageNo, Long typeid, HttpServletRequest req, ModelMap model) {
		BaseInfo base = (BaseInfo)req.getSession().getAttribute("base");
		Long relatedid = base.getId();
		if(pageNo==null) pageNo = 0;
		Integer limit = 15;
		Integer count = commonService.getGoodsCount(relatedid, typeid, name, Status.Y);
		List<Goods> goodsList = commonService.getGoodsList(relatedid, typeid, name, Status.Y, pageNo*limit, limit);
		
		Integer rowsPerPage = limit;
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/goodsList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("pageUtil", pageUtil);
		
		model.put("goodsList", goodsList);
		model.put("count", count);
		List<GoodsType> typeList = daoService.getAllObjects(GoodsType.class);
		model.put("typeList", typeList);
		return "company/goodsList.vm";
	}
	@RequestMapping("/auth/member/company/updateGoods.xhtml")
	public String updateGoods(Long id, ModelMap model) {
		Goods goods = daoService.getObject(Goods.class, id);
		goods.setStatus(Status.D);
		daoService.saveObject(goods);
		return showJsonSuccess(model);
	}
	
	@RequestMapping("/auth/member/company/orderList.xhtml")
	public String orderList(Long id, Integer pageNo,  HttpServletRequest req, ModelMap model) {
		if(pageNo==null) pageNo = 0;
		Integer limit = 15;
		Integer count = commonService.getOrderCount(null, id, null, null);
		List<GoodsOrder> orderList = commonService.getOrderList(null, id, null, null, pageNo*limit, limit);
		
		Integer rowsPerPage = limit;
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/orderList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("pageUtil", pageUtil);
		
		model.put("orderList", orderList);
		model.put("count", count);
		return "company/orderList.vm";
	}
	@RequestMapping("/auth/member/company/userList.xhtml")
	public String orderList(Long shopid, SearchCommand command, Integer pageNo,  ModelMap model) {
		if(pageNo==null) pageNo=0;
		Integer limit = 15;
		Integer count = commonService.getUserCount(shopid, command, Status.Y);
		List<User> userList = commonService.getUserList(shopid, command, Status.Y, pageNo*limit, limit);
		Map<Long, Shop> shopMap = new HashMap<Long, Shop>();
		for(User user : userList){
			Shop shop = daoService.getObject(Shop.class, user.getCsid());
			shopMap.put(user.getId(), shop);
		}
		Integer rowsPerPage = limit;
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/userList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("userList", userList);
		model.put("pageUtil", pageUtil);
		model.put("shopMap", shopMap);
		return "company/userList.vm";
	}
	@RequestMapping("/auth/member/company/shopList.xhtml")
	public String shopList(Long proxyid, SearchCommand command, Integer pageNo,  ModelMap model) {
		if(pageNo==null) pageNo=0;
		Integer limit = 15;
		Integer count = commonService.getShopCount(proxyid, command, Status.Y);
		List<Shop> shopList = commonService.getShopList(proxyid, command, Status.Y, pageNo*limit, limit);
		Map<Long, Proxy> proxyMap = new HashMap<Long, Proxy>();
		for(Shop shop : shopList){
			Proxy proxy = daoService.getObject(Proxy.class, shop.getProxyid());
			proxyMap.put(shop.getId(), proxy);
		}
		Integer rowsPerPage = limit;
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/shopList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("shopList", shopList);
		model.put("pageUtil", pageUtil);
		model.put("proxyMap", proxyMap);
		return "company/shopList.vm";
	}
	@RequestMapping("/auth/member/company/planList.xhtml")
	public String planList(String name, Integer pageNo,  ModelMap model) {
		if(pageNo==null) pageNo=0;
		Integer limit = 15;
		Integer count = commonService.getPlanCount(null, name, Status.Y);
		List<Plan> planList = commonService.getPlanList(null, name, Status.Y, pageNo*limit, limit);
		Map<Long, Proxy> proxyMap = new HashMap<Long, Proxy>();
		for(Plan plan : planList){
			if(!proxyMap.containsKey(plan.getRelatedid())) {
				Proxy proxy = daoService.getObject(Proxy.class, plan.getRelatedid());
				proxyMap.put(plan.getRelatedid(), proxy);
			}
		}
		Integer rowsPerPage = limit;
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/planList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("planList", planList);
		model.put("pageUtil", pageUtil);
		model.put("proxyMap", proxyMap);
		return "company/planList.vm";
	}
	@RequestMapping("/auth/member/company/planDetail.xhtml")
	public String planList(Long id,  ModelMap model) {
		Plan plan = daoService.getObject(Plan.class, id);
		if(!StringUtils.equals(plan.getRead(), "Y")) {
			plan.setRead("Y");
			daoService.saveObject(plan);
		}
		model.put("plan", plan);
		return "proxy/planDetail.vm";
	}
	@RequestMapping("/auth/member/company/elegantForm.xhtml")
	public String elegantForm(ModelMap model){
		Elegant elegant = daoService.getObject(Elegant.class, Config.sysID);
		model.put("elegant", elegant);
		return "company/elegantForm.vm";
	}
	@RequestMapping("/auth/member/company/saveElegant.xhtml")
	public String saveElegant(String content, ModelMap model){
		Elegant elegant = daoService.getObject(Elegant.class, Config.sysID);
		if(elegant==null) {
			elegant = new Elegant();
			elegant.setRelatedid(Config.sysID);
		}
		elegant.setContent(content);
		daoService.saveObject(elegant);
		return "redirect:/auth/public/elegant.xhtml";
	}
	
	
	@RequestMapping("/auth/member/company/cultureForm.xhtml")
	public String cultureForm(ModelMap model){
		Culture culture = daoService.getObject(Culture.class, Config.sysID);
		model.put("culture", culture);
		return "company/cultureForm.vm";
	}
	@RequestMapping("/auth/member/company/saveCulture.xhtml")
	public String saveCulture(String content, ModelMap model){
		Culture culture = daoService.getObject(Culture.class, Config.sysID);
		if(culture==null) {
			culture = new Culture();
			culture.setRelatedid(Config.sysID);
		}
		culture.setContent(content);
		daoService.saveObject(culture);
		return "redirect:/auth/public/culture.xhtml";
	}
	
	@RequestMapping("/auth/member/company/newsForm.xhtml")
	public String newsForm(Long id, ModelMap model){
		if(id!=null) {
			News news = daoService.getObject(News.class, id);
			model.put("news", news);
		}
		return "company/newsForm.vm";
	}
	@RequestMapping("/auth/member/company/newsList.xhtml")
	public String newsList(Integer pageNo, String name, ModelMap model) {
		if(pageNo==null) pageNo = 0;
		Integer limit = 15;
		Integer rowsPerPage = limit;
		Integer count = commonService.getNewsCount(Config.sysID, name, Status.Y);
		List<News> newsList = commonService.getNewsList(Config.sysID, name, Status.Y, pageNo*limit, limit);
		
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/newsList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("pageUtil", pageUtil);
		
		model.put("count", count);
		model.put("newsList", newsList);
		return "company/newsList.vm";
	}
	@RequestMapping("/auth/member/company/saveNews.xhtml")
	public String saveNews(Long id, HttpServletRequest req, ModelMap model){
		News news = new News();
		if(id!=null) {
			news = daoService.getObject(News.class, id);
		}else {
			news.setRelatedid(Config.sysID);
		}
		try {
			bindData(news, req.getParameterMap());
			String msg = ValidateUtil.validate(news, ",");
			if(StringUtils.isNotBlank(msg)) return showJsonFailure(msg, model);
			daoService.saveObject(news);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("id", news.getId());
		return "redirect:/auth/public/newsDetail.xhtml";
	}
	@RequestMapping("/auth/member/company/updateNews.xhtml")
	public String updateNews(Long id, ModelMap model){
		News news = daoService.getObject(News.class, id);
		news.setStatus(Status.D);
		daoService.saveObject(news);
		return showJsonSuccess(model);
	}
	@RequestMapping("/auth/member/company/discountList.xhtml")
	public String discountList(String name, Integer pageNo, ModelMap model) {
		if(pageNo==null) pageNo=0;
		Integer limit = 15;
		Integer count = commonService.getDiscountCount(Config.sysID, name, null, null, Status.Y);
		List<Discount> discountList = commonService.getDiscountList(Config.sysID, name, null, null, Status.Y, pageNo*limit, limit);
		Integer rowsPerPage = limit;
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/discountList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("pageUtil", pageUtil);
		
		model.put("count", count);
		model.put("discountList", discountList);
		return "company/discountList.vm";
	}
	@RequestMapping("/auth/member/company/discountForm.xhtml")
	public String discountForm(Long id, ModelMap model){
		if(id!=null) {
			Discount d = daoService.getObject(Discount.class, id);
			model.put("discount", d);
		}
		return "company/discountForm.vm";
	}

	@RequestMapping("/auth/member/company/saveDiscount.xhtml")
	public String saveDiscount(Long id, HttpServletRequest req, ModelMap model){
		Discount discount = new Discount();
		if(id!=null) {
			discount = daoService.getObject(Discount.class, id);
		}else {
			discount.setRelatedid(Config.sysID);
		}
		try {
			bindData(discount, req.getParameterMap());
			daoService.saveObject(discount);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("id", discount.getId());
		return "redirect:/auth/public/discountDetail.xhtml";
	}
	@RequestMapping("/auth/member/company/updateDiscount.xhtml")
	public String updateDiscount(Long id, ModelMap model){
		Discount discount = daoService.getObject(Discount.class, id);
		discount.setStatus(Status.D);
		daoService.saveObject(discount);
		return showJsonSuccess(model);
	}
	@RequestMapping("/auth/member/company/videoForm.xhtml")
	public String videoForm(Long id, ModelMap model){
		if(id!=null){
			Video video = daoService.getObject(Video.class, id);
			model.put("video", video);
		}
		return "company/videoForm.vm";
	}
	@RequestMapping("/auth/member/company/videoList.xhtml")
	public String videoList(String name, Integer pageNo, ModelMap model) {
		if(pageNo==null) pageNo = 0;
		Integer limit = 15;
		Integer count = commonService.getVideoCount(Config.sysID, name, Status.Y);
		List<Video> videoList = commonService.getVideoList(Config.sysID, name, Status.Y, pageNo*limit, limit);
		
		Integer rowsPerPage = limit;
		PageUtil pageUtil = new PageUtil(count, rowsPerPage, pageNo, "auth/member/company/videoList.xhtml");
		Map params = new HashMap();
		pageUtil.initPageInfo(params);
		model.put("pageUtil", pageUtil);
		
		model.put("count", count);
		model.put("videoList", videoList);
		return "company/videoList.vm";
	}
	
	@RequestMapping("/auth/member/company/saveVideo.xhtml")
	public String saveVideo(Long id, HttpServletRequest req, ModelMap model) throws IOException{
		Video video = new Video();
		if(id!=null) {
			video = daoService.getObject(Video.class, id);
		}else {
			video.setRelatedid(Config.sysID);
		}
		try {
			bindData(video, req.getParameterMap());
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
			MultipartFile file = multipartRequest.getFile("file");
			if(file!=null && file.getSize()>0) {
				byte[] buffer = new byte[1024];
				int len = -1;
				InputStream in = file.getInputStream();
				String fileName = StringUtil.getNewFileName(file);
				String path = req.getSession().getServletContext().getRealPath("/upload/flash") + "/" + fileName;
				OutputStream out = new FileOutputStream(path);
				while ((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				in.close();
				out.close();
				video.setPath("upload/flash/"+fileName);
			}
			file = multipartRequest.getFile("vlogo");
			if(file!=null && file.getSize()>0){
				byte[] buffer = new byte[1024];
				int len = -1;
				InputStream in = file.getInputStream();
				String fileName = StringUtil.getNewFileName(file);
				String path = req.getSession().getServletContext().getRealPath("/upload/images") + "/" + fileName;
				OutputStream out = new FileOutputStream(path);
				while ((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
				}
				in.close();
				out.close();
				video.setVlogo("upload/images/"+fileName);
			}
			daoService.saveObject(video);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.put("id", video.getId());
		return "redirect:/auth/public/videoDetail.xhtml";
	}
	@RequestMapping("/auth/member/company/updateVideo.xhtml")
	public String updateVideo(Long id, ModelMap model){
		Video video = daoService.getObject(Video.class, id);
		video.setStatus(Status.D);
		daoService.saveObject(video);
		return showJsonSuccess(model);
	}
	
	@RequestMapping("/auth/member/company/qqList.xhtml")
	public String qqList(ModelMap model){
		List<QQInfo> qqList = commonService.getQQInfoList(1L);
		model.put("qqList", qqList);
		return "company/qqList.vm";
	}
	@RequestMapping("/auth/member/company/delQQ.xhtml")
	public String delQQ(Long id, ModelMap model){
		QQInfo qq = daoService.getObject(QQInfo.class, id);
		daoService.removeObject(qq);
		return showJsonSuccess(model);
	}
	@RequestMapping("/auth/member/company/saveQQ.xhtml")
	public String saveQQ(String qq, ModelMap model){
		QQInfo info = new QQInfo();
		info.setRelatedid(Config.sysID);
		info.setQq(qq);
		daoService.saveObject(info);
		return showJsonSuccess(model);
	}
	@RequestMapping("/auth/member/company/goodsTypeList.xhtml")
	public String goodsTypeList(ModelMap model){
		List<GoodsType> typeList = daoService.getAllObjects(GoodsType.class);
		model.put("typeList", typeList);
		return "company/goodsTypeList.vm";
	}
	@RequestMapping("/auth/member/company/saveGoodsType.xhtml")
	public String saveGoodsType(Long id, String name, ModelMap model){
		GoodsType type = new GoodsType();
		if(id!=null) {
			type = daoService.getObject(GoodsType.class, id);
		}
		type.setName(name);
		daoService.saveObject(type);
		return showJsonSuccess(model);
	}
	@RequestMapping("/auth/member/company/videoToIndex.xhtml")
	public String videoToIndex(Long vid,  ModelMap model){
		Video video = daoService.getObject(Video.class, vid);
		video.setUpdatetime(new Timestamp(System.currentTimeMillis()));
		daoService.saveObject(video);
		return showJsonSuccess(model);
	}
	@RequestMapping("/auth/member/company/qxList.xhtml")
	public String goodsList(ModelMap model) {
		return "company/qxList.vm";
	}
}
